package org.example.traffic.superadmin;

import org.example.traffic.superadmin.SuperAdmin;
import org.example.traffic.superadmin.SuperAdminService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
/**
 * @author: wyk
 */
@RestController
@RequestMapping("/super-admin")
public class SuperAdminController {

    private final SuperAdminService superAdminService;

    public SuperAdminController(SuperAdminService superAdminService) {
        this.superAdminService = superAdminService;
    }

    // 注册接口，接收前端传来的超级管理员信息并保存到数据库
    @PostMapping("/register")
    public ResponseEntity<SuperAdmin> register(@RequestBody SuperAdmin superAdmin) {
        SuperAdmin registeredAdmin = superAdminService.register(superAdmin);
        return new ResponseEntity<>(registeredAdmin, HttpStatus.CREATED);
    }

    // 登录接口，根据服务层返回结果进行相应响应返回
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody SuperAdmin superAdmin) {
        try {
            Optional<SuperAdmin> loggedInAdmin = superAdminService.login(superAdmin.getUsername(), superAdmin.getPassword());
            if (loggedInAdmin.isPresent()) {
                return ResponseEntity.ok().body("Login successful");
            }
            return new ResponseEntity<>("Login failed", HttpStatus.UNAUTHORIZED);
        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    // 异常处理方法，处理服务层抛出的用户名已存在的异常
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
